import React from 'react';
import { Form, Select, Input, Button, Card, Row, Col, DatePicker, Popover } from 'antd';
import PageHeaderLayout from 'components/Layout/PageHeaderLayout';
import SearchPaymenters from './SearchPaymenters';
import { LwjUpload } from 'components';
import FooterToolbar from 'components/FooterToolbar';
import moment from 'moment';
import { uuid } from 'utils/utils';

const FormItem = Form.Item;
const Option = Select.Option;
const DoAddReceiptForm = ({
  doAdd,
  loading,
  paymentPattern,
  receiptAccounts,
  currentReceipter,
  onSelectedReceipter,
  listProps,
  dispatch,
  paymentNumStatus,
  form: {
    getFieldDecorator,
    validateFieldsAndScroll,
    getFieldValue,
    setFieldsValue
  }
}) => {
  const breadcrumbList = [
    {
      title: '财务管理',
      href: '/'
    }, {
      title: '收款单',
      href: '/receipt'
    }, {
      title: '收款单添加',
      href: '/receiptAdd'
    }
  ];

  const config = {
    rules: [{ type: 'object', required: true, message: '请选择时间' }],
  };

  const prefixSelector = getFieldDecorator('prefix', {
    initialValue: '0',
  })(
    <Select id="pre" style={{ width: 70 }}>
      <Option value="0">用户</Option>
      <Option value="1">商家</Option>
    </Select>
  );

  const handleSubmit = (e) => {
    e.preventDefault();
    const submitPaymentTime = getFieldValue("paymentTime")
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        delete values.prefix
        delete values.paymentTime
        delete values.bankName_receipt
        delete values.branch_receipt
        delete values.bankAccount_receipt
        delete values.bankUserName_receipt
        delete values.bankName_payment
        delete values.branch_payment
        delete values.bankAccount_payment
        delete values.bankUserName_payment
        values.paymentTime = parseInt(submitPaymentTime.format('X'))
        doAdd(values)
      }
    });
  }

  const onSearchHandle = () => {
    dispatch({
      type: 'receiptAdd/query',
      payload: {}
    })
    listProps.showOrClosePop(true);
  }

  let selectedRecord = currentReceipter;

  const handleChange = (value) => {
    if (receiptAccounts !== undefined) {
      receiptAccounts.map(function (item) {
        if (item.id === value) {
          selectedRecord = item;
          dispatch({
            type: 'receiptAdd/updateReceipter',
            payload: {
              receipter: selectedRecord,
            }
          })
          if (getFieldValue("paymentType") === "网银") {
            setFieldsValue({ paymentNum: moment(_.now()).format("YYYYMMDDHHmm") + item.name })
          }
        }
      })
    }
  }

  const upProps = {
    target: '/services/upload/receipt',
    accept: 'image/*,.pdf,.dwg,.dwf,.zip,.rar,.xlsx,.xls',
    uploadIcon: 'upload',
    fileType: '',
    showUploadList: true
  }
  const receipterContent = <div>
    <div>
      <span>开户账号：</span><span className="ant-form-text">{
        onSelectedReceipter === undefined ? selectedRecord.defaultBankAccount : onSelectedReceipter.bankAccount
      }</span></div>
    <div>
      <span>开户银行：</span><span className="ant-form-text">{
        onSelectedReceipter === undefined ? selectedRecord.defaultBankName : onSelectedReceipter.bankName
      }</span></div>
    <div>
      <span>开户名：</span><span className="ant-form-text">{
        onSelectedReceipter === undefined ? selectedRecord.defaultBankUserName : onSelectedReceipter.bankUserName
      }</span></div>
  </div>
  const onChange = (record) => {
    if (record === "现金") {
      setFieldsValue({ paymentNum: moment(_.now()).format("YYYYMMDD") + "B" + uuid(10, 10) })
    } else if (record === "网银") {
      setFieldsValue({ paymentNum: moment(_.now()).format("YYYYMMDDHHmm") + (_.isEmpty(onSelectedReceipter) ? currentReceipter.defaultName : onSelectedReceipter.name) })
      console.info(currentReceipter)
    } else {
      setFieldsValue({ paymentNum: "" })
    }
  }
  return (
    <PageHeaderLayout title="添加收款单" breadcrumbList={breadcrumbList} bordered={false}>
      {receiptAccounts !== undefined &&
        <Form onSubmit={handleSubmit} >
          <Row gutter={20}>
            <Card type="inner" title="收付款方信息">
              <div style={{ marginLeft: 300 }}>
                <FormItem
                  label="付款方:"
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 8 }}>
                  {getFieldDecorator('paymenterId', {
                    rules: [{ required: true, message: '此项不能为空' }],
                  })(
                    <div className="gutter-example">
                      <Row >
                        <Col span={23}>
                          <Input value={listProps.currentRecord !== undefined ? listProps.currentRecord.name : ""} disabled={true} />
                        </Col>
                        <Col span={1}>
                          <Button style={{ marginLeft: 2 }} type="primary" icon="search" onClick={onSearchHandle} />
                        </Col>
                      </Row>
                      <SearchPaymenters {
                        ...listProps
                      } />
                    </div>
                  )}
                </FormItem>
                <div >
                  <div style={{ display: 'inline' }}>
                    <FormItem
                      label="收款方:"
                      labelCol={{ span: 4 }}
                      wrapperCol={{ span: 8 }}
                    >
                      {getFieldDecorator('receipterId', {
                        rules: [{ required: true, message: '此项不能为空' }],
                        initialValue: currentReceipter.defaultId
                      })(
                        <Select style={{ width: 405 }} autoFocus={true} onChange={handleChange} >
                          {
                            receiptAccounts.map(function (item) {
                              return (<Option value={item.id} key={item.id}> {item.name} </Option>)
                            }
                            )
                          }
                        </Select>
                      )}
                    </FormItem>
                  </div>
                  <div style={{ position: 'absolute', marginLeft: 620, marginTop: -53 }}>
                    <Popover placement="right" title='收款方详情' content={receipterContent} trigger="click">
                      <a >详情</a>
                    </Popover>
                  </div>
                </div>
              </div>
            </Card>
          </Row>
          <Row style={{ marginTop: 15 }}>
            <Card type="inner" title="支付信息">
              <Col span={8}>
                <FormItem
                  label="应收金额"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('receivable', {
                    rules: [
                      { required: true, whitespace: true, message: "请输入正确的金额" },
                      { pattern: '^\\d+(\\.\\d+)?$', whitespace: true, message: "请输入正确的金额" }
                    ],
                  })(
                    <Input type='number' />
                  )}
                </FormItem>
                <FormItem
                  label="实收金额"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('received', {
                    rules: [
                      { required: true, message: '请输入正确的金额' },
                      { pattern: '^\\d+(\\.\\d+)?$', whitespace: true, message: "请输入正确的金额" }
                    ],
                  })(
                    <Input type='number' />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label="支付方式:"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {!_.isEmpty(paymentPattern) && getFieldDecorator('paymentType', {
                    rules: [{ required: true, message: '此项不能为空' }],
                  })(
                    <Select onChange={onChange} >
                      {
                        paymentPattern.map(function (item) {
                          return (<Option value={item.name} key={item.name} > {item.name} </Option>)
                        }
                        )
                      }
                    </Select>
                  )}
                </FormItem>

              </Col>
              <Col span={8}>
                <FormItem
                  label="支付时间"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('paymentTime', config)(
                    <DatePicker onChange={() => {
                    }} />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label="支付凭证:"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('paymentNum', {
                    // validateTrigger:['onBlur','onFocus','onChange'],
                    rules: [
                      { required: true, message: '此项不能为空' },
                      // {
                      //   validator: (rule, value, callback) => {
                      //     if(_.isEmpty(value)){
                      //       callback()
                      //       return
                      //     }
                      //     dispatch({
                      //       type: 'receiptAdd/checkPaymentNum',
                      //       payload: value
                      //     })
                      //     callback(paymentNumStatus)
                      //     return ;
                      //   }
                      // }
                    ]
                  })(
                    <Input disabled={(getFieldValue("paymentType") === "现金" || getFieldValue("paymentType") === "网银")} />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label="上传附件:"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('attachments', {
                    rules: [{ required: true, message: '此项不能为空' }],
                  })(
                    <LwjUpload {...upProps} />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label="备注:"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 10 }}
                >
                  {getFieldDecorator('memo', {
                    rules: [{ required: true, message: '此项不能为空' }],
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
            </Card>
          </Row>
          <FooterToolbar style={{
            width: '100%'
          }}>
            <Button loading={loading.global} type="primary" htmlType="submit">
              提交
            </Button>
          </FooterToolbar>
        </Form>}
    </PageHeaderLayout>
  );
};

export default Form.create()(DoAddReceiptForm);
